<?
	session_start();
	include('conn.php');
	$obj = json_decode($_REQUEST["dataset"]);
	$opt = $_REQUEST["q"];
	$user=$_SESSION['username'];
	
	switch($opt){
		case 'c':			
			$tdt = $obj->termdt;	
			
			$qrystb = "select st.id as stid,ct.id as ctid,c.CustId from stbTable st, cardTable ct, Customer c 
			where st.stbno = '$obj->stbno' and ct.cardno = '$obj->cardno' and c.CustomerName = '$obj->custname'";
			$resstb = mysql_query($qrystb);	
			while($rowstb = mysql_fetch_array($resstb)){
				$stbid = $rowstb['stid'];
				$cardid = $rowstb['ctid'];
				$custid = $rowstb['CustId'];
			}				
			
			$qryp = "select pairid from STBDetails where Active='1' and stbid='$stbid' and cardid='$cardid';";
			$resp = mysql_query($qryp);	
			$rowp = mysql_fetch_array($resp);
			$pairid = $rowp['pairid'];			
						
			$qry = "insert into STBtoCustomer (CustId,stbid,cardid,pairid,ActivationDate,TerminationDate,Ratepermonth,enteredby,entereddate,status) 
			values('$custid', '$stbid','$cardid' ,'$pairid','$obj->actdt', 
			case when ".strlen($tdt)." > 2 then '".date("Y-m-d H:i:s", strtotime($obj->termdt))."' else NULL end,
			'$obj->rpm','$user','".date('Y-m-d H:i:s')."','1');";				
			$res = mysql_query($qry);			
			echo "<br> $qryp <br> $qry - $res";
			break;
		
		case 'u':
			$id = $obj->id;
			$qrystb = "select st.id as stid,ct.id as ctid,c.CustId from stbTable st, cardTable ct, Customer c 
			where st.stbno = '$obj->stbno' and ct.cardno = '$obj->cardno' and c.CustomerName = '$obj->custname'";
			$resstb = mysql_query($qrystb);	
			while(mysql_fetch_array($resstb))
				$rowstb = mysql_fetch_array($resstb);
			$stbid = $rowstb['stid'];
			$cardid = $rowstb['ctid'];
			$custid = $rowstb['CustId'];
			
			$qryp = "select pairid from STBDetails where Active='1' and stbid='$stbid' and cardid='$cardid';";
			$resp = mysql_query($qryp);	
			$rowp = mysql_fetch_array($resp);
			$pairid = $rowp['pairid'];			
			
			$qry = "update STBtoCustomer
			set CustId= '$custid',stbid= '$stbid',pairid='$pairid' ,
			ActivationDate= case when ".strlen($obj->actdt)." > 2 then '".date("Y-m-d H:i:s", strtotime($obj->actdt))."' else NULL end, 
			RateperMonth= '$obj->rpm',cardid='$cardid',
			modifiedby = '$user', modifieddate = '".date('Y-m-d')."' where stbtocustid='$id';";	
			echo "$qrystb <br> $qry <br>";
			$res = mysql_query($qry);	
			echo $res;
			
			break;
			
		case 'd':
			$id = $_REQUEST['id'];				
			$qry = "update STBtoCustomer set status='9' where stbtocustid='$id';";		
			echo "<br> $qry <br>";
			$res = mysql_query($qry);		
			break;
		
		default:
			echo "No option selected";
	}
?>